﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq.SqlClient;
using System.Data.SqlClient;
using System.Web;
using System.Web.Mvc;
using Kunlun.Models;
using Kunlun.ViewModels;
using Kunlun.BusinessLogic;
namespace Kunlun.Controllers {
	[HandleError]
	public class MyKunlunController : Controller {
		
		KunLunEntities entities = new KunLunEntities();
		KunlunAddress address = new KunlunAddress();

		#region 我的卡擦
		[Authorize]
		public ActionResult Index() {
			if (Request.Cookies.Get("userId").Value != null) {
				int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value);
				Kunlun.Models.Consumer user = entities.Consumers.Single(u => u.ID == userid);

				return View(user);
			} else {
				return RedirectToAction("Index", "Home");
			}

		}

		[Authorize]
		public ActionResult ConsumerEdit() {
			if (Request.Cookies.Get("userId").Value != null) {
				int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value.ToString());
				Kunlun.Models.Consumer user = entities.Consumers.Single(u => u.ID == userid);

				return View(user);
			} else {
				return RedirectToAction("Index", "Home");
			}

		}

		[Authorize]
		[HttpPost]
		public ActionResult ConsumerEdit(FormCollection collection) {
			if (Request.Cookies.Get("userId").Value != null) {
				int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value);
				Kunlun.Models.Consumer user = entities.Consumers.Single(u => u.ID == userid);
				UpdateModel(user);
				entities.SaveChanges();
				return RedirectToAction("Index", "MyKunlun");
			} else {
				return RedirectToAction("Index", "Home");
			}

		}

		[Authorize]
		public ActionResult AddressEdit(int id) {
			try {
				if (ModelState.IsValid) {
					Address address = entities.Address.Single(a => a.AddressID == id);
					ViewBag.Pid = new SelectList(entities.Provice, "provinceID", "proviceName", address.Pid);
					City city = entities.City.FirstOrDefault(c => c.cityID == address.Cid);
					ViewBag.Cid = new SelectList(entities.City.Where(c => c.fatherID == city.fatherID), "cityID", "cityName", address.Cid);
					Area area = entities.Area.FirstOrDefault(a => a.fatherID == address.Areas);
					ViewBag.Areas = new SelectList(entities.Area.Where(a => a.fatherID == a.fatherID), "areaID", "areaName", address.Areas);
					return View(address);
				} else {
					return RedirectToAction("Index", "Home");
				}
			} catch {
				return RedirectToAction("Index", "Home");
			}


		}

		[Authorize]
		[HttpPost]
		public ActionResult AddressEdit(FormCollection collection, int id) {
			try {
				if (ModelState.IsValid) {


					Address address = entities.Address.Single(a => a.AddressID == id);
					entities.Entry(address).State = System.Data.EntityState.Modified;
					UpdateModel(address);
					entities.SaveChanges();
					string url = Request["path"];
					if (url != null) {
						return Redirect(url);
					}

					return RedirectToAction("Index", "MyKunlun");
				} else {
					return RedirectToAction("Index", "Home");
				}
			} catch (Exception ex) {
				WebLog.ErrorLog(ex);
				return RedirectToAction("Index", "Home");
			}

		}

		[Authorize]
		public ActionResult AddressAdd() {
			ViewBag.Pid = new SelectList(entities.Provice, "provinceID", "proviceName");
			List<SelectListItem> list = new List<SelectListItem>();
			list.Add(new SelectListItem() { Value = "", Text = "请选择" });
			ViewBag.Cid = list;
			ViewBag.Areas = list;
			return View();
		}

		[Authorize]
		[HttpPost]
		public ActionResult AddressAdd(Address address) {
			string Redirecturl = "/MyKunlun/Index";
			if (Request["url"] != null) {
				Redirecturl = Request["url"];
			}

			if (ModelState.IsValid) {

				int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value);
				address.Uid = userid;
               
				address.BeginDate = DateTime.Now;
				address.LastUpdateTime = DateTime.Now;
				entities.Address.Add(address);
				entities.SaveChanges();
				return Redirect(Redirecturl);
			}
			return Redirect(Redirecturl);

		}

		[Authorize]
		public ActionResult AddressList() {
			int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value);

			var addresslist = entities.Address.Where(a => a.Uid == userid).ToList();
			return View(addresslist);
		}

		[Authorize]
		[HttpPost]
		public ActionResult RemoveAddress(int id) {
			address.DeleteAddress(id);
			return Json(true, JsonRequestBehavior.AllowGet);
		}
		#endregion

		#region 我的购物车
        /// <summary>
        /// 客户购物车
        /// </summary>
        public ActionResult Cart()
        {
            var list = KunlunCarts.GetCars(true);               //客户购物车显示实体列表
            ViewBag.AllPrice = KunlunCarts.Allprice;

            return View(list);
        }

		/// <summary>
		/// 放入购物车
		/// </summary>
		/// <param name="productid">产品编号</param>
		/// <param name="attrid">规格编号</param>
		/// <param name="type">购买类型（1，无框画，2海报，3框画）</param>
		/// <param name="smallid">每个产品以"|"隔开，0位表示框，1位表示1层卡纸，2位表示2层卡纸，3位表示3层卡纸，4位表示玻璃，空位以0补足，0|1|2|3）</param>
		/// <param name="worksid">作品编号</param>
		/// <param name="scores">积分</param>
		/// <param name="propertys">属性</param>
        [HttpPost]
        public ActionResult Cart(string info)
        {
            string[] items = info.Split('|');
            int ind = KunlunCarts.MaxItems();
            foreach (string item in items)
            {
                string[] str = item.Split(',');
                string pid = str[0];
                int attrID = Convert.ToInt32(str[1]);
                FrameType ft = (FrameType)Convert.ToInt32(str[2]);
                PaperLevel level = (PaperLevel)Convert.ToInt32(str[3]);
                PaperSize size = (PaperSize)Convert.ToInt32(str[4]);
                int nu = Convert.ToInt32(str[5]);
                int workID = Convert.ToInt32(str[6]);
                KunlunCarts.InsertCart(pid, attrID, ft, level, size, ind, workID, nu);
            }

            return Json(true, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 清空购物车
        /// </summary>
        public ActionResult ClearCart()
        {
            KunlunCarts.ClearCar();

            return RedirectToAction("Cart");
        }

        public ActionResult CartProduct(string id)
        {
            ProductsViewModels p = Kunlun.BusinessLogic.KunlunProduct.GetProductByID(id);
            return PartialView(p);
        }

		public ActionResult CartAttributes(string id) {
			int attid = int.Parse(id);
			Product_attributes plist = entities.Product_attributes.FirstOrDefault(s => s.ID == attid);
			return PartialView(plist);
		}

		[HttpGet]
		public ActionResult DeleteCarts(string index) {
			List<UserCartViewModels> list = KunlunCarts.DeleteCart(int.Parse(index));
			CartViewModel model = new CartViewModel();

			model.AllPrice = KunlunCarts.Allprice;
			model.Product = KunlunCarts.Product;
			model.Message = model.Product + "从购物车中删除";
			return Json(model, JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		public ActionResult ModifyCarts(string id, string number) {

			List<UserCartViewModels> list = KunlunCarts.ModifyCart(int.Parse(id), int.Parse(number));
			CartViewModel model = new CartViewModel();

			model.AllPrice = KunlunCarts.Allprice;
			model.Product = KunlunCarts.Product;
			model.ID = int.Parse(id);
			model.Message = model.Product + "从被修改";
			return Json(model, JsonRequestBehavior.AllowGet);
		}

        public ActionResult GetCarts()
        {
            CartViewModel model = new CartViewModel();
            model.AllPrice = KunlunCarts.Allprice;
            model.Count = KunlunCarts.GetCarCount();
            return Json(model, JsonRequestBehavior.AllowGet);
        }
		#endregion

		#region 我的订单
		[Authorize]
		public ActionResult Purchase() {
			int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value);
			PurchaseView model = new PurchaseView();
			model.Address = (entities.Address.Where(a => a.Uid == userid)).ToList();

			if (model.Address.Count == 0) {
				return Redirect("/MyKunlun/AddressAdd?url=/MyKunlun/Purchase");

			}
			model.Paymethod = entities.Paymethod.Where(p => p.isVisible == true).ToList();
			model.UserCartViewModels = KunlunCarts.GetCars(true);
			ViewBag.AllPrice = KunlunCarts.Allprice;
			model.DeliveType = entities.DeliveType.Where(d => d.IsVisible == true).ToList();
			return View(model);
		}

        [Authorize]
        public ActionResult CreateOrder(string addressid, string sendid, string payid, string invoice)
        {
            string orderid = new KunlunOrder().CreateOrder(addressid, sendid, payid, invoice);

            KunlunCarts.ClearCar(); //清理购物车信息

            return Json(orderid, JsonRequestBehavior.AllowGet);
        }

		[Authorize]
		public ActionResult OrderPay(string id) {
			string Host = "http://" + HttpContext.Request.ServerVariables["SERVER_NAME"].ToString();
			int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value);
			Order order = entities.Order.FirstOrDefault(o => o.Oid == id && o.UserID == userid);
            try {
				if (order != null && order.Status < 1) {
					Consumer user = entities.Consumers.FirstOrDefault(u => u.ID == userid);
					ViewBag.User = user;
					decimal _myMoney = user.LeaveMoney - @user.Scoring / 10;
					if (_myMoney > order.Price + order.Sendprice)
						ViewBag.PayPrice = "0.00";
					else
						ViewBag.PayPrice = order.Price + order.Sendprice - user.LeaveMoney - @user.Scoring / 10;

					return PartialView(order);
				} else {
					return Redirect("/MyKunlun/Order");
				}
            }
            catch (Exception ex)
                {
               
                WebLog.ErrorLog(ex);
                return Redirect("/MyKunlun/Order");
                }
		}
		#region 支付
		[Authorize]
		public ActionResult OrderPayAction(string id) {

			string Host = "http://" + HttpContext.Request.ServerVariables["SERVER_NAME"].ToString();
			int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value);
			Order order = entities.Order.FirstOrDefault(o => o.Oid == id);
			Consumer user = entities.Consumers.FirstOrDefault(u => u.ID == userid);
			ViewBag.User = user;
			decimal _myMoney = user.LeaveMoney - user.Scoring / 10;
			decimal PayMoney = order.Price + order.Sendprice;
			if (_myMoney > PayMoney) {
				if (PayMoney > user.Scoring / 10) {
					PayMoney = PayMoney - user.Scoring / 10;
					user.Scored = user.Scored + user.Scoring;
					order.Scored = user.Scoring;
					user.LeaveMoney = user.LeaveMoney - PayMoney;
					user.Scoring = 0;
					order.PayMoney = (decimal)0;
				} else {
					PayMoney = 0;
					user.Scored = user.Scored + (int)PayMoney * 10;
					order.Scored = (int)PayMoney * 10;
					user.LeaveMoney = user.LeaveMoney - PayMoney;
					user.Scoring = user.Scoring - (int)PayMoney * 10;
					order.PayMoney = (decimal)0;
				}
                if (order.Status < 1)
                    {
                    user.Scored = user.Scored + order.Scoring;
                    order.Status = 2;
                    entities.SaveChanges();
                    }
                return Redirect("/MyKunlun/Order");
			} else {
				PayMoney = PayMoney - _myMoney;
				user.Scored = user.Scored + user.Scoring;
				order.Scored = user.Scoring;
				user.LeaveMoney = 0;
				user.Scoring = 0;
				order.PayMoney = PayMoney;
			}
			if (order.Paymethod.Name == "货到付款") {
				if (order.Status < 1) {
					user.Scored = user.Scored + order.Scoring;
					order.Status = 2;
					entities.SaveChanges();
				}
				return Redirect("/MyKunlun/Order");
			}


			string url = new AliPay().ToURL(order.Oid, "框画", (Math.Round(PayMoney,2)).ToString(), user.Email, Host);
			return Redirect(url);


		}
		#endregion
        [Authorize]
        public ActionResult Order()
        {
            DateTime time = DateTime.Now.AddDays(-30);
            int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value);
            var order = (from o in entities.Order
                         where o.UserID == userid && o.Status > 1
                         orderby o.Oid descending
                         select o).ToList();
            ViewBag.OnComplete = (from o in entities.Order
                                  where o.UserID == userid && o.Status < 2 && o.BeginDate > time
                                  orderby o.Oid descending
                                  select o).ToList();

            return View(order);
        }

		public ActionResult AliNotify(FormCollection collection) {
			string result = new AliPay().GetURL(collection);
			if (result == "success") {
				string id = collection["out_trade_no"].ToString();
				string OrderFormID;
				if (id.Split('_').Length > 1) {
					OrderFormID = id.Split('_')[0];
				} else {
					OrderFormID = id;
				}
				int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value);
				Order order = entities.Order.FirstOrDefault(o => o.Oid == OrderFormID);
				Consumer user = entities.Consumers.FirstOrDefault(u => u.ID == order.UserID);
				decimal _myMoney = user.LeaveMoney - user.Scoring / 10;
				decimal PayMoney = order.Price + order.Sendprice;
				if (_myMoney > PayMoney) {
					if (PayMoney > user.Scoring / 10) {
						PayMoney = PayMoney - user.Scoring / 10;
						user.Scored = user.Scored + user.Scoring;
						order.Scored = user.Scoring;
						user.LeaveMoney = user.LeaveMoney - PayMoney;
						user.Scoring = 0;
						order.PayMoney = (decimal)0;
					} else {
						PayMoney = 0;
						user.Scored = user.Scored + (int)PayMoney * 10;
						order.Scored = (int)PayMoney * 10;
						user.LeaveMoney = user.LeaveMoney - PayMoney;
						user.Scoring = user.Scoring - (int)PayMoney * 10;
						order.PayMoney = (decimal)0;
					}
				} else {
					PayMoney = PayMoney - _myMoney;
					user.Scored = user.Scored + user.Scoring;
					order.Scored = user.Scoring;
					user.LeaveMoney = 0;
					user.Scoring = 0;
					order.PayMoney = PayMoney;
				}

				if (order.Status < 1) {
					order.Status = 2;
					entities.SaveChanges();
				}


			}
			return Content(result);
		}
		public ActionResult AliReturn(FormCollection collection) {
			string result = new AliPay().GetURL(collection);
			if (result == "success") {
				string id = collection["out_trade_no"].ToString();
				string OrderFormID;
				if (id.Split('_').Length > 1) {
					OrderFormID = id.Split('_')[0];
				} else {
					OrderFormID = id;
				}
				int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value);
				Order order = entities.Order.FirstOrDefault(o => o.Oid == OrderFormID);
				Consumer user = entities.Consumers.FirstOrDefault(u => u.ID == order.UserID);
				decimal _myMoney = user.LeaveMoney - user.Scoring / 10;
				decimal PayMoney = order.Price + order.Sendprice;
				if (_myMoney > PayMoney) {
					if (PayMoney > user.Scoring / 10) {
						PayMoney = PayMoney - user.Scoring / 10;
						user.Scored = user.Scored + user.Scoring;
						order.Scored = user.Scoring;
						user.LeaveMoney = user.LeaveMoney - PayMoney;
						user.Scoring = 0;
						order.PayMoney = (decimal)0;
					} else {
						PayMoney = 0;
						user.Scored = user.Scored + (int)PayMoney * 10;
						order.Scored = (int)PayMoney * 10;
						user.LeaveMoney = user.LeaveMoney - PayMoney;
						user.Scoring = user.Scoring - (int)PayMoney * 10;
						order.PayMoney = (decimal)0;
					}
				} else {
					PayMoney = PayMoney - _myMoney;
					user.Scored = user.Scored + user.Scoring;
					order.Scored = user.Scoring;
					user.LeaveMoney = 0;
					user.Scoring = 0;
					order.PayMoney = PayMoney;
				}
				if (order.Status < 1) {
					order.Status = 2;
					entities.SaveChanges();
				}


			}
			return Redirect("/MyKunlun/Order");
		}
		#endregion

		#region 推荐积分
		[Authorize]
		public ActionResult Recommend() {
			string userid = Request.Cookies.Get("userId").Value;
			ViewBag.URL = "http://" + HttpContext.Request.ServerVariables["SERVER_NAME"].ToString() + "/Recommend/" + userid;
			return View();
		}
		#endregion

        [Authorize]
		public ActionResult InsertCollection(string pid) {
			int userid = 0;
			if (!int.TryParse(Request.Cookies.Get("userId").Value, out userid)) {
				return Content("登录后才能进行收藏！");
			}
			int id = KunlunCollection.InsertProduct(userid, pid);
			return Content(id == 0 ? "该商品已经收藏过！" : "已经放入收藏夹！");
		}

        [Authorize]
		public ActionResult CollectionList() {
			int userid = 0;
			List<Product> list = new List<Product>();
			if (int.TryParse(Request.Cookies.Get("userId").Value, out userid)) {
		
				foreach(Cats c in KunlunCollection.GetProduct(userid)){
					Product p = KunlunProduct.GetProductModel(c.Pid);
					list.Add(p);
				}
			}
			ViewData.Model = list;
			return View("CollectionList");
		}

		public ActionResult DeleteCollection(string pid) {

			KunlunCollection.DeleteProduct(pid);
			return CollectionList();
		}

		[HttpGet]
		[Authorize]
		public ActionResult Preferential() {
			int userid = 0;
			if (int.TryParse(Request.Cookies.Get("userId").Value, out userid)) {
				ViewData["Codes"] = KunlunFavourableCode.GetCodes(userid);
			} else {
				ViewData["Codes"] = new List<FavourableCode>();
			}
			return View();
		}

        [Authorize]
        public ActionResult Points()
        {
            int userid = int.Parse(Request.Cookies.Get("userId").Value);
            Consumer user = entities.Consumers.FirstOrDefault(u => u.ID == userid);
            return View(user);   
        }
			
	}
}
